package com.yingside.gui;

import sun.jvm.hotspot.runtime.JavaVFrame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

public class TestKeyEventFrame extends JFrame {

    private JTextField txtInput;

    public TestKeyEventFrame(){
        this.setTitle("键盘事件窗口");
        this.setBounds(300,300,400,400);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setLayout(new FlowLayout());
        txtInput = new JTextField(20);

        txtInput.addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
//                System.out.println("e.getKeyChar() = " + e.getKeyChar());
                if(e.getKeyChar() >= 'a' && e.getKeyChar() <= 'z'){
                    return;
                }else{
                    e.consume();
                }
            }

            public void keyPressed(KeyEvent e){
//                System.out.println("e.getKeyCode() = " + e.getKeyCode());
//                System.out.println("KeyEvent.(e.getKeyCode()) = " + KeyEvent.getKeyText(e.getKeyCode()));

//                if(e.getKeyCode() >= 65 && e.getKeyCode() <= 90){
//                    System.out.println("e.getKeyChar() = " + e.getKeyChar());
//                }
//                String str = txtInput.getText();
//                txtInput.setText(str.substring(0,str.length()-1));

            }

            public void keyReleased(KeyEvent e){

                if(e.getKeyCode() >= 65 && e.getKeyCode() <= 90){
                    return;
                }
//                String str = txtInput.getText();
//                txtInput.setText(str.substring(0,str.length()-1));
            }
        });

        this.add(txtInput);
    }

    public static void main(String[] args) {
        TestKeyEventFrame keyEventFrame = new TestKeyEventFrame();
        keyEventFrame.setVisible(true);

    }
}
